package com._21cn.framework.utils;

import java.util.List;
import java.util.Map;

/**
 * SQL拼接工具类
 * @author 司徒海富
 */
public class SqlBuilder {
	protected final StringBuilder statement = new StringBuilder();

	public SqlBuilder(String state) {
		this.statement.append(state);
	}
	
	/**
	 * 追加SQL片段
	 */
	public SqlBuilder appendStatement(String statement) {
		this.statement.append(statement);
		return this;
	}

	/**
	 * 返回拼接的SQL
	 */
	public String toStatement() {
		return this.statement.toString();
	}

	@Override
	public String toString() {
		return this.statement.toString();
	}

	/**
	 * 组装where条件sql
	 * @param params
	 * @return
	 */
	public SqlBuilder combineWhere( Map<String, Object> params ){
		SqlBuilder where = new SqlBuilder("where 1 = 1");
		if( params!=null ){
			for(Map.Entry<String, Object> en : params.entrySet()){
				String key = en.getKey();
				Object value = en.getValue();
				if(value!=null && !StringUtil.isEmpty(value.toString()) && key.startsWith("eq")){
					key = key.substring(2, key.length()).toLowerCase();
					where.appendStatement(" and "+ key + "= '" + value + "'");
				}
				if(value!=null && !StringUtil.isEmpty(value.toString()) && key.startsWith("like")){
					key = key.substring(4, key.length()).toLowerCase();
					where.appendStatement(" and "+ key + "like '%" + value + "%'");
				}
				if(value!=null && !StringUtil.isEmpty(value.toString()) && key.startsWith("gt")){
					key = key.substring(2, key.length()).toLowerCase();
					where.appendStatement(" and "+ key + "> '" + value + "'");
				}
				if(value!=null && !StringUtil.isEmpty(value.toString()) && key.startsWith("lt")){
					key = key.substring(2, key.length()).toLowerCase();
					where.appendStatement(" and "+ key + "< '" + value + "'");
				}
				if(value!=null && key.startsWith("in") && key.endsWith("List")){
					key = key.substring(2, key.length());
					key = key.substring(0, key.length()-4).toLowerCase();
					List<Object> inList = (List<Object>)value;
					String ins = getIns(inList);
					if(!StringUtil.isEmpty(ins)){
						where.appendStatement(" and "+ key + " in (" + ins + ")");
					}
				}
			}
		}
		String sql = this.toStatement().replace("#where#", where.toStatement());
		return new SqlBuilder(sql);
	}

	private String getIns(List<Object> list){
		String ins = "";
		if( list.size()>0 ){
			for (Object item : list){
				ins = ins +",'"+ item +"'";
			}
			ins = ins.substring(1);
		}
		return ins;
	}

}
